package com.itheima.course.design.ui;

import com.itheima.course.design.entity.Course;
import com.itheima.course.design.entity.Enrollment;
import com.itheima.course.design.service.CourseService;
import com.itheima.course.design.service.EnrollmentService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class StudentUI extends JFrame {
    private CourseService courseService = new CourseService();
    private EnrollmentService enrollmentService = new EnrollmentService();
    private String studentId;

    public StudentUI(com.itheima.course.design.entity.Student student) {
        this.studentId = student.getStudentId();
        initUI(student.getName());
    }

    private void initUI(String studentName) {
        setTitle("学生选课系统 - " + studentName);
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();

        // 课程列表面板
        JPanel coursePanel = new JPanel(new BorderLayout());
        DefaultListModel<Course> courseListModel = new DefaultListModel<>();
        JList<Course> courseList = new JList<>(courseListModel);
        courseList.setCellRenderer(new CourseListCellRenderer());
        JScrollPane courseScrollPane = new JScrollPane(courseList);
        coursePanel.add(courseScrollPane, BorderLayout.CENTER);

        JButton refreshButton = new JButton("刷新课程列表");
        JButton enrollButton = new JButton("选课");
        JButton exitButton = new JButton("退出系统");

        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(refreshButton);
        buttonPanel.add(enrollButton);
        buttonPanel.add(exitButton);
        coursePanel.add(buttonPanel, BorderLayout.SOUTH);

        // 我的课程面板
        JPanel myCoursePanel = new JPanel(new BorderLayout());
        DefaultListModel<Enrollment> enrollmentListModel = new DefaultListModel<>();
        JList<Enrollment> enrollmentList = new JList<>(enrollmentListModel);
        enrollmentList.setCellRenderer(new EnrollmentListCellRenderer());
        JScrollPane enrollmentScrollPane = new JScrollPane(enrollmentList);
        myCoursePanel.add(enrollmentScrollPane, BorderLayout.CENTER);

        JButton refreshMyButton = new JButton("刷新我的课程");
        JButton unenrollButton = new JButton("退选课程");
        JButton backButton = new JButton("返回登录界面");

        JPanel myButtonPanel = new JPanel(new FlowLayout());
        myButtonPanel.add(refreshMyButton, BorderLayout.WEST);
        myButtonPanel.add(unenrollButton, BorderLayout.CENTER);
        myButtonPanel.add(backButton, BorderLayout.EAST);
        myCoursePanel.add(myButtonPanel, BorderLayout.SOUTH);

        // 将面板添加到选项卡
        tabbedPane.addTab("所有课程", coursePanel);
        tabbedPane.addTab("我的课程", myCoursePanel);

        panel.add(tabbedPane, BorderLayout.CENTER);

        add(panel);

        // 刷新课程列表事件
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshCourseList(courseListModel);
            }
        });

        // 选课按钮事件
        enrollButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (courseList.getSelectedValue() == null) {
                    JOptionPane.showMessageDialog(StudentUI.this, "请先选择一门课程！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Course selectedCourse = courseList.getSelectedValue();
                boolean success = enrollmentService.addEnrollment(new Enrollment(null, studentId, selectedCourse.getCourseCode()));
                
                if (success) {
                    JOptionPane.showMessageDialog(StudentUI.this, "选课成功！");
                    refreshCourseList(courseListModel);
                    refreshEnrollmentList(enrollmentListModel);
                } else {
                    JOptionPane.showMessageDialog(StudentUI.this, "选课失败，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
                }
                
            }
        });

        // 退出按钮事件
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // 刷新我的课程列表事件
        refreshMyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshEnrollmentList(enrollmentListModel);
            }
        });

        // 退选按钮事件
        unenrollButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (enrollmentList.getSelectedValue() == null) {
                    JOptionPane.showMessageDialog(StudentUI.this, "请先选择一门要退选的课程！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Enrollment selectedEnrollment = enrollmentList.getSelectedValue();
                boolean success = enrollmentService.deleteEnrollment(studentId, selectedEnrollment.getCourseCode());
                
                if (success) {
                    JOptionPane.showMessageDialog(StudentUI.this, "退选成功！");
                    refreshCourseList(courseListModel);
                    refreshEnrollmentList(enrollmentListModel);
                } else {
                    JOptionPane.showMessageDialog(StudentUI.this, "退选失败，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 返回登录界面按钮事件
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MainUI().setVisible(true);
                dispose();
            }
        });

        // 初始化加载数据
        refreshCourseList(courseListModel);
        refreshEnrollmentList(enrollmentListModel);
    }

    // 刷新课程列表
    private void refreshCourseList(DefaultListModel<Course> model) {
        model.clear();
        List<Course> courses = courseService.getAllCourses();
        for (Course course : courses) {
            model.addElement(course);
        }
    }

    // 刷新选课列表
    private void refreshEnrollmentList(DefaultListModel<Enrollment> model) {
        model.clear();
        List<Enrollment> enrollments = enrollmentService.getEnrollmentsByStudentId(studentId);
        for (Enrollment enrollment : enrollments) {
            // 获取课程信息
            Course course = courseService.getCourseByCode(enrollment.getCourseCode());
            if (course != null) {
                // 使用新的displayCourseCode字段
                enrollment.setDisplayCourseCode(course.getName() + " (" + course.getCourseCode() + ")");
            }
            model.addElement(enrollment);
        }
    }

    // 课程列表渲染器
    private static class CourseListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Course) {
                Course course = (Course) value;
                setText(course.getName() + " (课程代码: " + course.getCourseCode() + ", 教师: " + course.getInstructor() + ")");
            }
            return this;
        }
    }

    // 选课列表渲染器
    private static class EnrollmentListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Enrollment) {
                Enrollment enrollment = (Enrollment) value;
                // 使用displayCourseCode进行显示
                setText(enrollment.getDisplayCourseCode());
            }
            return this;
        }
    }
}